<template>
  <div id="answerResultView">
    <h1 style="text-align: center">{{ answer.questionBankName }}</h1>
    <h2 style="text-align: center">得分：{{answer.score}}</h2>
    <h3 style="text-align: center">答题结果分析：</h3>
    <!-- 修改为显示逐字输出的结果 -->
    <a-typography-text style="white-space: pre-wrap;">{{ analyzeResult }}</a-typography-text>
    <div v-if="(selectQuestions && selectQuestions.length > 0) || (judgeQuestions && judgeQuestions.length > 0)">
      <a-affix>
        <a-anchor line-less boundary="center" style="width: 100%" :change-hash="false">
          <div v-if="selectResult && selectResult.length > 0">
            <h3>选择题</h3>
            <div style="display: flex">
              <a-anchor-link :href="'#'+index" v-for="(item, index) in selectResult" :key="index">
                <a-avatar :size="25" shape="square" :style="{ backgroundColor: item===1 ? 'green' : 'red'}">
                  {{ index + 1 }}
                </a-avatar>
              </a-anchor-link>
            </div>
          </div>
          <div v-if="judgeResult && judgeResult.length > 0">
            <h3>判断题</h3>
            <div style="display: flex">
              <a-anchor-link :href="'#'+(index+selectQuestions.length)" v-for="(item, index) in judgeResult" :key="index">
                <a-avatar :size="25" shape="square" :style="{ backgroundColor: item===1 ? 'green' : 'red'}">
                  {{ index + 1 + selectQuestions.length }}
                </a-avatar>
              </a-anchor-link>
            </div>
          </div>
        </a-anchor>
      </a-affix>

      <h2 style="text-align: center">答题详情</h2>
      <!-- <a-list>定义了一个滚动列表 -->
      <a-list :scrollbar="scrollbar" :bordered="false">
        <!-- 选择题区域 -->
        <a-list-item v-for="(item , index) in selectQuestions" :key="item.id">
          <!-- <a-list>定义了滚动列表下的每一个题目-->
          <a-list>
            <template #header>
              {{ index + 1 }}.{{ item.content }}
            </template>
            <a-radio-group :id="index" direction="vertical" :default-value="selections.get(item.id)" disabled="true">
              <a-radio
                  class="option"
                  v-for="option in item.options"
                  :value="option.key"
                  :key="option.key"
              >
                {{ option.key }}.{{ option.value }}
              </a-radio>
            </a-radio-group>
            <template #footer>
              <span v-if="item.answer === selections.get(item.id)">
                <IconCheck style="color: green"></IconCheck>
              </span>
              <span v-else>
                <IconClose style="color: red"></IconClose>
              </span>
              正确答案：{{ item.answer }}
            </template>
          </a-list>
        </a-list-item>
        <!-- 判断题区域 -->
        <a-list-item v-for="(item , index) in judgeQuestions" :key="item.id">
          <!-- <a-list>定义了滚动列表下的每一个题目-->
          <a-list>
            <template #header>
              {{ index + 1 + selectQuestions.length}}.{{ item.content }}
            </template>
            <a-radio-group :id="index + selectQuestions.length" direction="vertical" :default-value="selections.get(item.id)" :disabled="true">
              <a-radio
                  class="option"
                  value="1"
              >
                A.正确
              </a-radio>
              <a-radio
                  class="option"
                  value="0"
              >
                B.错误
              </a-radio>
            </a-radio-group>
            <template #footer>
              <span v-if="item.isCorrect == selections.get(item.id)">
                <IconCheck style="color: green"></IconCheck>
              </span>
              <span v-else>
                <IconClose style="color: red"></IconClose>
              </span>
              正确答案：{{ item.answer }}
            </template>
          </a-list>
        </a-list-item>
        <a-list-item>
          <a-row align="center">
            <a-col align="center">
              <a-button type="primary" @click="clickAnswer">重新作答</a-button>
            </a-col>
          </a-row>
        </a-list-item>
      </a-list>
    </div>
    <div v-else>
      <template>
        <a-empty/>
      </template>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import {useRoute, useRouter} from "vue-router";

import {IconCheck, IconClose} from "@arco-design/web-vue/es/icon";
import {getAnswerResultVOByIdUsingGet} from "@/api/AnswerResultRequest";
import {getQuestionByBankId} from "@/api/QuestionRequest";
import {jsonToMap} from "@/utils/ConvertUtil";

// 答题记录的判题信息，数组中只有0和1,0代表错误，1代表正确
let selectResult = ref([]);
let judgeResult = ref([]);

// 题目列表
let selectQuestions = ref([]);
let judgeQuestions = ref([]);

// 路由变量
const route = useRoute();
const router = useRouter();

// 当前答题记录的ID
let answerId = route.params.answerId;

// 每个题目的选项信息，Key为questionId，Value为ABC或者0 1
let selections = new Map();

// 当前答题记录对象AnswerResultVO
let answer = ref({});

// 新增：用于存储逐字输出的分析结果
const analyzeResult = ref('');

onMounted(async () => {
  // 查询答题记录
  let answerResult = await getAnswerResultVOByIdUsingGet(answerId);
  // 获取题库ID
  let bankId = answerResult.data.data.questionBankId;
  // 根据题库ID获取题目信息
  let response = await getQuestionByBankId(bankId);
  response.data.data.forEach((question) => {
    if (question.type === 0) {
      selectQuestions.value.push(question);
    } else if (question.type === 1) {
      judgeQuestions.value.push(question);
    }
  });
  // 设置答题记录响应式变量
  answer.value = answerResult.data.data;
  // 获取用户的选项信息
  let options = answerResult.data.data.options;
  // 将JSON转换为Map
  selections = jsonToMap(options);
  console.log(selections)
  // 获取判题信息，这段逻辑正确的前提是数据库存储的判题信息是按照选择题，判断题的顺序存储的。
  let result = JSON.parse(answerResult.data.data.judgeOptions);
  let i = 0;
  for (; i < selectQuestions.value.length; i++) {
    selectResult.value.push(result[i]);
  }
  for (; i < judgeQuestions.value.length + selectQuestions.value.length; i++) {
    judgeResult.value.push(result[i]);
  }
  if(answer.value.analyzeResult === null || answer.value.analyzeResult === undefined || answer.value.analyzeResult===""){
    console.log("正在调用AI分析");
    const eventSource = new EventSource("http://localhost:8101/api/answer/analyze/"+ answerResult.data.data.id);
    eventSource.onmessage = function (message){
      // 逐字追加分析结果
      const msg = message.data.replace(/\\x0A/g , '\n');
      analyzeResult.value += msg;
    };
    eventSource.onerror = function (event){
      if(event.eventPhase === EventSource.CLOSED) {
        eventSource.close();
      }
    };
  }else{
    analyzeResult.value = answer.value.analyzeResult;
  }
});

function clickAnswer() {
  router.push("/answerQuestion/" + answer.value.questionBankId)
}
</script>

<style scoped>
#answerResultView {
  padding-left: 200px;
  margin-right: 200px;
}

/* 新增的样式，让 a-anchor-link 在一行显示，超出换行 */
.anchor-link-container {
  display: flex;
}
</style>